// 当前消息类型
let currentType = 2; // 默认显示新闻

// 加载消息列表
async function loadMessages(type) {
    try {
        const response = await API.message.search({
            mtype: type
        });

        const messageList = document.getElementById('messageList');
        messageList.innerHTML = '';
        
        if (Array.isArray(response)) {
            // 只显示对应类型的消息
            const filteredMessages = response.filter(message => message.mtype === type);
            
            filteredMessages.forEach(message => {
                const card = document.createElement('div');
                card.className = 'message-card';
                card.onclick = () => {
                    window.location.href = `detail.html?mid=${message.mid}&type=${type}`;
                };
                
                card.innerHTML = `
                    <h2>${message.head}</h2>
                    <div class="message-meta">
                        <span>${new Date(message.mtime).toLocaleDateString()}</span>
                    </div>
                    <div class="message-preview">${message.context.substring(0, 200)}...</div>
                `;
                
                messageList.appendChild(card);
            });
        }
    } catch (error) {
        console.error('加载列表失败:', error);
    }
}

// 更新导航状态
function updateNavigation(type) {
    document.querySelectorAll('.nav-link').forEach(link => {
        link.classList.toggle('active', parseInt(link.dataset.type) === type);
    });
}

// 更新用户信息
function updateUserInfo() {
    const userInfo = JSON.parse(localStorage.getItem('userInfo'));
    if (userInfo && userInfo.uid) {
        document.getElementById('userInfo').innerHTML = `
            <span>欢迎，${userInfo.uid}</span>
            <a href="javascript:void(0)" onclick="handleLogout()">退出</a>
        `;
    }
}

// 退出登录
function handleLogout() {
    localStorage.removeItem('userInfo');
    window.location.href = '../login.html';
}

// 页面加载完成后执行初始化
document.addEventListener('DOMContentLoaded', () => {
    // 检查登录状态
    const userInfo = JSON.parse(localStorage.getItem('userInfo'));
    if (!userInfo || userInfo.utype !== 1) {
        window.location.href = '../login.html';
        return;
    }

    // 获取URL参数中的类型，默认为新闻
    const params = new URLSearchParams(window.location.search);
    const type = parseInt(params.get('type')) || 2;
    currentType = type;

    // 初始化页面
    updateNavigation(type);
    loadMessages(type);
    updateUserInfo();

    // 添加导航点击事件
    document.querySelectorAll('.nav-link').forEach(link => {
        link.addEventListener('click', (e) => {
            e.preventDefault();
            const newType = parseInt(e.target.dataset.type);
            currentType = newType;
            
            updateNavigation(newType);
            loadMessages(newType);
            history.pushState(null, '', `?type=${newType}`);
        });
    });
}); 